package com.ujson.base.domain.repository.impl;

import com.ujson.base.domain.entity.Aggregate;
import com.ujson.base.domain.entity.EntityDiff;
import com.ujson.base.domain.entity.Identifier;
import com.ujson.base.domain.repository.AggregateManager;

public class ThreadLocalAggregateManager<T extends Aggregate<ID>, ID extends Identifier> implements AggregateManager<T, ID> {
    private Class<T> targetClass;
    private ThreadLocal<DBContext<T, ID>> context;

    public ThreadLocalAggregateManager(Class<T> targetClass) {
        this.targetClass = targetClass;
        this.context = ThreadLocal.withInitial(() -> new DBContext<>(targetClass));
    }

    @Override
    public void attach(T aggregate) {
        this.context.get().attach(aggregate);
    }

    @Override
    public void detach(T aggregate) {
        this.context.get().detach(aggregate);
    }

    @Override
    public void merge(T aggregate) {
        this.context.get().merge(aggregate);
    }

    @Override
    public EntityDiff detectChanges(T aggregate) throws IllegalAccessException {
        return this.context.get().detectChanges(aggregate);
    }


}
